<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true" :okAuth="'proj:contract:pmContractborrow:edit'"
    @register="registerDrawer" @ok="handleSubmit" width="40%">
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" ref="formRef" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProjContractPmContractborrowForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmContractborrow,
    pmContractborrowSave,
    pmContractborrowForm,
  } from '/@/api/proj/contract/pmContractborrow';
  import { pmContract2TreeData } from '/@/api/proj/contract/pmContract2';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);
  const formRef = ref();
  const { t } = useI18n('proj.contract.pmContractborrow');
  const { showMessage } = useMessage();
  const record = ref < PmContractborrow > ({} as PmContractborrow);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增合同借阅') : t('编辑合同借阅'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目名称'),
      field: 'projectcode',
      fieldLabel: 'proname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        immediate: true,
        onChange: (e) => {
          const values = formRef.value.getFieldsValue();
          // values.projectcode = node.extra.prono;
          // values.proname = node.extra.proname;
          values.htname = '';
          values.contractcode = '';
          values.contractcode2 = '';
          values.htname2 = '';
          formRef.value.setFieldsValue(values);


          updateSchema([
            {
              field: 'contractcode2',
              componentProps: {
                params: {
                  prono: e
                },
              }
            },
          ]);
        },
      },
      required: true,
    },
    {
      label: t('项目编号'),
      field: 'projectcode',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        readonly: true,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('资料类型'),
      field: 'borrowtype',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'zf_constract_zi_type',
        allowClear: true,
        default: '1',
        onChange: (e) => {
          if (e == '1' || e == '2') {
            const values = formRef.value.getFieldsValue();
            // values.projectcode = '';
            // values.proname = '';
            values.htname = '';
            values.contractcode = '';
            values.htname2 = '';
            values.contractcode2 = '';
            values.borrowtype = e;
            formRef.value.setFieldsValue(values);
            if (e == '2') {
              updateSchema([
                { field: 'contractcode2', ifShow: false },
                { field: 'contractcode', dynamicDisabled: false },
                { field: 'htname', ifShow: true },
              ]);
            } else if (e == '1') {
              updateSchema([
                { field: 'contractcode2', ifShow: true },
                { field: 'contractcode', dynamicDisabled: true },
                { field: 'htname', ifShow: false },
              ]);
            }
          }
        },
      },
      required: true,
    },
    {
      label: t('资料编号'),
      field: 'contractcode',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      required: true,
    },
    {
      label: t('资料名称'),
      field: 'htname',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      ifShow: false,
      required: true,
    },
    {
      label: t('资料名称'),
      field: 'contractcode2',
      fieldLabel: 'htname',
      component: 'TreeSelect',
      componentProps: {
        api: pmContract2TreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        onSelect: (value, node, extra) => {
          const values = formRef.value.getFieldsValue();
          values.projectcode = node.extra.prono;
          values.proname = node.extra.proname;
          values.htname = node.extra.name;
          values.contractcode = node.extra.code;
          values.contractcode2 = node.extra.prono;
          values.htname2 = node.extra.name;
          formRef.value.setFieldsValue(values);
        },
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    {
      label: t('借阅人'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      required: true,
    },
    {
      label: t('联系电话'),
      field: 'phoneno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      required: true,
    },
    {
      label: t('身份证号'),
      field: 'personidcardno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
    },
    {
      label: t('工号'),
      field: 'workno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
    },
    {
      label: t('预计归还'),
      field: 'expectedreturndate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
    },
    // {
    //   label: t('工程编号'),
    //   field: 'projectcode',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {
    //     maxlength: 50,
    //   },
    // },
    // {
    //   label: t('工程名称'),
    //   field: 'proname',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {
    //     maxlength: 50,
    //   },
    // },
  ];

  const [registerForm, { resetFields, updateSchema, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmContractborrowForm(data);
    record.value = (res.pmContractborrow || {}) as PmContractborrow;
    record.value.__t = new Date().getTime();

    record.value.contractcode2 = record.value.htname
    let borrowtype = record.value.borrowtype
    if (borrowtype == '2') {
      updateSchema([
        { field: 'contractcode2', ifShow: false },
        { field: 'contractcode', dynamicDisabled: false },
        { field: 'htname', ifShow: true },
      ]);
    } else if (borrowtype == '1') {
      updateSchema([
        {
          field: 'contractcode2', ifShow: true, componentProps: {
            params: {
              prono: record.value.projectcode
            },
          }
        },
        { field: 'contractcode', dynamicDisabled: true },
        { field: 'htname', ifShow: false },
      ]);
    }
    setDrawerProps({ showOkBtn: record.value.isreturn == '1' ? false : true });
    await setFieldsValue(record.value);

    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // console.log('submit', params, data, record);
      const res = await pmContractborrowSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>